package cn.dapeng;

import java.lang.reflect.Method;

/**
 * @BelongProject Test
 * @BelongPackage ref
 * @Description TODO
 * @ClassName StaticTest
 * @Author xupenghong
 * @Date 2024/8/23 13:43
 * @Version 1.0.0
 */
public class StaticTest {

    /**
     * 静态方法反射
     *
     * @param name
     * @return
     */
    public static String hello(String name) {
        return "hello " + name;
    }

    /**
     * 成员方法反射
     */
    public void hi() {
        System.out.println("hi call ......");
    }

    public static void main(String[] args) throws Exception {
        Class<StaticTest> clazz = StaticTest.class;

        // 类静态方法反射
        Method method = clazz.getMethod("hello", String.class);
        String result = (String) method.invoke(null, "dapeng");
        System.out.println(result);

        // 类成员方法反射
        Method m1 = clazz.getDeclaredMethod("hi");
        StaticTest instance = clazz.getConstructor().newInstance();
        m1.invoke(instance);

        // 构造器实例化
        Method m2 = clazz.getDeclaredMethod("createBeanByConstructor");
        Student student = (Student) m2.invoke(instance);
        System.out.println(student);

        // 工厂方法实例化
        Method m3 = clazz.getDeclaredMethod("factoryMethod");
        student = (Student) m3.invoke(instance);
        System.out.println(student);
    }


    public Student createBeanByConstructor() {
        Class<Student> type = Student.class;
        try {
            return type.getConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Student factoryMethod() {
        return new Student();
    }

}
